package com.xtz.controller;

import ch.qos.logback.core.rolling.helper.TokenConverter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import com.xtz.domain.Employee;
import com.xtz.dto.AddEmployeeDto;
import com.xtz.service.AdminEmployeeService;
import com.xtz.vo.EmployeePageVo;
import com.xtz.vo.EmployeeVo;
import com.xtz.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * date: 2022/5/7 18:48
 *
 * @author xietianze
 */
@RestController
@RequestMapping("employee")
public class EmployeeController {
    @Autowired
    private AdminEmployeeService adminEmployeeService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping()
    public Result addEmployee(@RequestBody AddEmployeeDto dto){
        if (Objects.isNull(dto)){
            return new Result(0,"参数不能为空",null,null);
        }
        Employee employee1 = adminEmployeeService.selectByUsername(dto.getUsername());
        if (employee1 !=null){
            return new Result(0,dto.getUsername()+"已存在",null,null);
        }else{
            Employee employee = new Employee();

            BeanUtils.copyProperties(dto,employee);
            Boolean result = adminEmployeeService.addEmployee(employee);
            Integer code = result ? 1:0;
            String msg = result? "添加成功":"已存在，添加失败";

            return new Result(code,msg,null,null);
        }

    }


    @GetMapping("/page")
    public Result getEmployeePage(HttpServletRequest request,
                                  @RequestParam(value = "name",required = false) String name,
                                  @RequestParam(value = "page",defaultValue = "1")Integer page,
                                  @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize){



        List<Employee> employeePage = adminEmployeeService.getEmployeePage(name, page, pageSize);


        Long employeeAmount = adminEmployeeService.getEmployeeAmount(name);
        EmployeePageVo employeePageVo = new EmployeePageVo();
        employeePageVo.setCurrent(page);
        employeePageVo.setRecords(employeePage);
        employeePageVo.setSize(pageSize);
        employeePageVo.setTotal(employeeAmount);

        return new Result(1,"查询成功",employeePageVo,null);

    }

    @PutMapping()
    public Result updateEmployee(@RequestBody Employee employee){

        Boolean aBoolean = adminEmployeeService.updateEmployeeById(employee);
        int code = aBoolean ? 1:0;
        String data = aBoolean ? "修改成功":"修改失败";

        return new Result(code,null,data,null);
    }

    @PostMapping("/login")
    public Result loginEmployee(@RequestBody Employee employee){
        //1.将页面提交的密码password进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2.查询数据库
        Employee emp = adminEmployeeService.login(employee.getUsername(),password);
        //3.如果没有查询到则返回登录失败结果
        if (Objects.isNull(emp)){
            return new Result(500,"账号或密码错误，或账号已停用",null,null);
        }
        //4.生成token
        String tokenString = System.currentTimeMillis() + emp.getId();
        String token = DigestUtils.md5DigestAsHex(tokenString.getBytes());

        //将token记录到redis
        redisTemplate.opsForValue().set(token, JSON.toJSONString(emp),259200,TimeUnit.SECONDS);

        EmployeeVo employeeVo = new EmployeeVo();
        BeanUtils.copyProperties(emp,employeeVo);
        employeeVo.setToken(token);

        return new Result(1,"登录成功",employeeVo,null);
    }
    @PostMapping("/logout")
    public Result LoginOut(HttpServletRequest request){
        String token = request.getHeader("Authorization");

        redisTemplate.delete(token);
        return new Result(1,null,"退出成功",null);
    }

    @GetMapping("/{id}")
    public Result selectEmployee(@PathVariable String id){
        if (StringUtils.isNullOrEmpty(id)){
            return null;
        }
        Employee employee = adminEmployeeService.selectEmployeeById(id);


        return new Result(1,null,employee,null);
    }

}
